package com.agile.leetcode.pic;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 测试使用文字生成图片
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/12 22:25
 */
public class GeneratePicByScript {
    /**
     * 从文件读取文字
     *
     * @param filePath
     * @return
     */
    public static List<String> readScript(String filePath) throws IOException {
        List<String> list = new ArrayList<>();
        File file = new File(filePath);
        // 创建输入流
        try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
            try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                String temp = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    list.add(temp);
                }
            }
        }
        return list;
    }

    /**
     * @param content
     * @throws IOException
     */
    public static void generatePic(String content) throws IOException {
        // 设置宽高
        int width = 400;
        int height = 400;
        // 设置路径及名称
        String path = "D:\\" + content + ".jpg";
        System.out.println("文件名" + path);
        File file = new File(path);
        // 字体
        Font font = new Font("黑体", Font.BOLD, 60);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.setBackground(getRandomColor());
        graphics.clearRect(0, 0, width, height);
        graphics.setFont(font);
        FontMetrics fontMetrics = graphics.getFontMetrics(font);
        int textWidth = fontMetrics.stringWidth(content);
        graphics.setPaint(new Color(0, 0, 128));
        // 设置图片水平居中
        int widthX = (width - textWidth) / 2;
        graphics.drawString(content, widthX, 220);
        ImageIO.write(bufferedImage, "jpg", file);
    }

    private static Color getRandomColor() {
        Random random = new Random();
        // 我这边设置了返回浅色的图片，排除了深色
        return new Color(random.nextInt(255) % (255 - 230 + 1) + 200, random.nextInt(255) % (255 - 230 + 1) + 200, random.nextInt(255) % (255 - 230 + 1) + 200);
    }

    public static void main(String[] args) throws IOException {
        String path = "D:\\czk.txt";
        List<String> list = readScript(path);
        for (String s : list) {
            generatePic(s);
        }
    }
}
